package org.hxyjs.dao.impl;

import org.hxyjs.dao.ExpertDao;
import org.hxyjs.entity.Expert;
import org.hxyjs.mapper.ExpertMapper;
import org.hxyjs.page.PageInfo;
import org.hxyjs.utils.GenNumTools;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Repository("expertDao")//一般实现类不会直接生成默认对象名 而是使用 接口的默认对象名
public class ExpertDaoImpl implements ExpertDao {
    @Resource //autowired 会装配能够直接扫描到的对象  resource spring容器运行的时候才找到需要的对象  注入
    private ExpertMapper expertMapper;

    //查询全部
    public List<Expert> getAllExperts() throws Exception {
        return expertMapper.selectByExample(null);
    }

    //按主键查询
    @Override
    public Expert getExpertByEno(String eno) throws Exception {
        return expertMapper.selectByPrimaryKey(eno);
    }

    //分页查询
    @Override
    public List<Expert> getExpertByPage(PageInfo pageInfo) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("currPage", pageInfo.getCurrPage());
        map.put("pageSize", pageInfo.getPageSize());
        int itemCount = (int) expertMapper.countByExample(null);
        pageInfo.setItemCount(itemCount);
        return expertMapper.getExpertByPage(map);
    }

    //删除
    @Override
    public Integer deleteExpertByEno(String eno) {
        return expertMapper.deleteByPrimaryKey(eno);
    }

    //修改
    @Override
    public Integer updateExpertByEno(Expert expert) {
        return expertMapper.updateByPrimaryKey(expert);
    }


    //增加
    @Override
    public Integer addExpert(Expert expert) {
        expert.setEno(initId());
        return expertMapper.insertSelective(expert);
    }

    public String initId() {
        String maxEno = expertMapper.getMaxEno();
        maxEno = Optional.ofNullable(maxEno).orElse("0000");
        return GenNumTools.initId("e", 4, maxEno);
    }


}